package com.tss.service.impl;

import com.tss.dao.DestinationDAO;
import com.tss.dao.TicketTypeDAO;
import com.tss.dao.TransactionRecordDAO;
import com.tss.dao.impl.DestinationDAOImpl;
import com.tss.dao.impl.TicketTypeDAOImpl;
import com.tss.dao.impl.TransactionRecordDAOImpl;
import com.tss.model.Destination;
import com.tss.model.TicketType;
import com.tss.model.TransactionRecord;
import com.tss.service.DeviceService;
import com.tss.service.TicketService;

import java.util.List;

/**
 * 购票流程控制实现类
 */
public class TicketServiceImpl implements TicketService {
    private DestinationDAO destinationDAO;
    private TicketTypeDAO ticketTypeDAO;
    private TransactionRecordDAO transactionRecordDAO;
    private DeviceService deviceService;

    public TicketServiceImpl() {
        this.destinationDAO = new DestinationDAOImpl();
        this.ticketTypeDAO = new TicketTypeDAOImpl();
        this.transactionRecordDAO = new TransactionRecordDAOImpl();
        this.deviceService = new DeviceServiceImpl();
    }

    @Override
    public boolean validateDestination(String code) {
        Destination destination = destinationDAO.selectByCode(code);
        return destination != null;
    }

    @Override
    public double calculateTotal(String ticketType, String category, int quantity) {
        List<TicketType> types = ticketTypeDAO.selectByType(ticketType);
        for (TicketType type : types) {
            if (type.getCategory().equals(category)) {
                return type.getPrice() * quantity;
            }
        }
        return 0;
    }

    @Override
    public boolean completeTransaction(TransactionRecord record) {
        boolean success = transactionRecordDAO.insert(record);
        
        if (success) {
            // 获取目的地名称
            Destination destination = destinationDAO.selectByCode(record.getDestCode());
            if (destination != null) {
                // 打印车票
                String[] ticketInfo = record.getTicketType().split("-");
                String ticketType = ticketInfo[0].trim();
                String category = ticketInfo[1].trim();
                deviceService.printTicket(destination.getName(), ticketType, category, record.getAmount(), 1);
            }
        }
        
        return success;
    }

    @Override
    public boolean cancelTransaction(int transactionId) {
        return transactionRecordDAO.cancelTransaction(transactionId);
    }
} 